package com.yuke.cloud.service.cmc.service.impl;

import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.core.utils.RequestUtil;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.opc.dto.UploadFile;
import com.yuke.cloud.service.api.opc.service.OpcFileFeignApi;
import com.yuke.cloud.service.api.pmc.dto.FactoryInfoDto;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.dto.RegionInfoDto;
import com.yuke.cloud.service.api.pmc.exceptions.PmcBizException;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.exceptions.SmcBizException;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.cmc.dao.CmsAppTopicDataMapper;
import com.yuke.cloud.service.cmc.dto.CmsAppIds;
import com.yuke.cloud.service.cmc.dto.CmsAppTopicDataDetailDto;
import com.yuke.cloud.service.cmc.entity.CmsAppTopicData;
import com.yuke.cloud.service.cmc.service.CmsAppTopicDataService;
import com.yuke.cloud.service.cmc.service.CmsAppTopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by wg on 2019/01/18.
 */
@Slf4j
@Service
@Transactional
public class CmsAppTopicDataServiceImpl extends BaseService<CmsAppTopicData> implements CmsAppTopicDataService {
    @Resource
    private CmsAppTopicDataMapper cmsAppTopicDataMapper;

    @Resource
    private CmsAppTopicService cmsAppTopicService;
    @Resource
    private OpcFileFeignApi opcFileFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private WmcStorageFeignApi wmcFeignApi;

    @Override
    public int save(CmsAppTopicData record) {
        record.setUpdateUser(RequestUtil.getLoginUser().getUserId());
        return super.save(record);
    }

    @Override
    public int update(CmsAppTopicData entity) {
        entity.setUpdateUser(RequestUtil.getLoginUser().getUserId());
        int count = super.update(entity);
        if (count > 0) {
            if (entity.getOldPicUrl() != null) {
                UploadFile uploadFile = new UploadFile();
                List<String> filePaths = new ArrayList<>();
                filePaths.add(entity.getOldPicUrl());
                uploadFile.setFilePaths(filePaths);
                opcFileFeignApi.filesDelete(uploadFile);
            }
        }
        return count;
    }

    @Override
    public CmsAppTopicData findById(Long id, Boolean isPassByChildTopic) {
        CmsAppTopicData cmsAppTopicData = super.findById(id);
        if (isPassByChildTopic != null && isPassByChildTopic) {
            cmsAppTopicData.setTopicName(this.selectByKey(cmsAppTopicData.getTopicId()).getDataName());
        } else {
            cmsAppTopicData.setTopicName(cmsAppTopicService.selectByKey(cmsAppTopicData.getTopicId()).getTopicName());
        }

        return cmsAppTopicData;
    }

    @Override
    public void deleteByIds(String ids) {
        List<Long> dataIds = Arrays.asList(ids.split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
//        List<CmsAppTopicData> cmsAppTopicDataList = cmsAppTopicDataMapper.selectByIds(ids);
        List<CmsAppTopicData> cmsAppTopicDataList = cmsAppTopicDataMapper.getDataListByIds(dataIds);
        super.deleteByIds(ids);
        this.deleteFile(cmsAppTopicDataList);
    }

    private void deleteFile(List<CmsAppTopicData> cmsAppTopicDataList) {
        UploadFile uploadFile = new UploadFile();
        List<String> filePaths = new ArrayList<>();
        for (CmsAppTopicData cmsAppTopicData : cmsAppTopicDataList) {
            if (cmsAppTopicData.getOldPicUrl() != null && !"".equals(cmsAppTopicData.getOldPicUrl()))
                filePaths.add(cmsAppTopicData.getOldPicUrl());
        }
        uploadFile.setFilePaths(filePaths);
        opcFileFeignApi.filesDelete(uploadFile);
    }

    @Override
    public int deleteByTopicIds(String ids) {
        List<Long> topicIds = Arrays.asList(ids.split(",")).stream().map(topicId -> Long.valueOf(topicId)).collect(Collectors.toList());
        List<CmsAppTopicData> cmsAppTopicDataList = cmsAppTopicDataMapper.selectByIds(ids);
        int count = cmsAppTopicDataMapper.deleteByTopicIds(topicIds);
        if (count > 0) {
            this.deleteFile(cmsAppTopicDataList);
        }
        return count;
    }

    @Override
    public int updateList(List<CmsAppTopicData> cmsAppTopicDatas) {
        int count = 0;
        for (CmsAppTopicData cmsAppTopicData : cmsAppTopicDatas) {
            count += this.update(cmsAppTopicData);
        }
        return count;
    }

    @Override
    public List<CmsAppTopicData> listByCondition(CmsAppTopicData cmsAppTopicData) {
        return cmsAppTopicDataMapper.listByCondition(cmsAppTopicData);
    }

    @Override
    public List<CmsAppTopicDataDetailDto> getAppListByTopicIds(CmsAppIds cmsAppIds) {
        List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos = new ArrayList<>();
        if (cmsAppIds == null || cmsAppIds.getIds() == null || cmsAppIds.getIds().equals("")) {
            return cmsAppTopicDataDetailDtos;
        }
        List<Long> topicIds = Arrays.asList(cmsAppIds.getIds().split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        return cmsAppTopicDataMapper.getAppListByTopicIds(topicIds);
    }

    @Override
    public List<ProdSpecInfoDto> getAppDetailByTopicId(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto) {
        log.info("--- Enter getAppDetailByTopicId(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto)，参数：{} ---", cmsAppTopicDataDetailDto);
        List<ProdSpecInfoDto> prodSpecInfoDtos = new ArrayList<>();
        if (cmsAppTopicDataDetailDto == null || cmsAppTopicDataDetailDto.getTopicId() == null || cmsAppTopicDataDetailDto.getTopicId().equals("")) {
            return prodSpecInfoDtos;
        }
        if (cmsAppTopicDataDetailDto!=null){
            if (cmsAppTopicDataDetailDto.getShopId()==null){
                cmsAppTopicDataDetailDto.setShopId(220854931912392704L);
            }
        }
        //List<Long> topicIds = Arrays.asList(cmsAppTopicDataDetailDto.getTopicId().split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        List<Long> topicIds = new ArrayList<>();
        topicIds.add(cmsAppTopicDataDetailDto.getTopicId());

        List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos = cmsAppTopicDataMapper.getAppListByTopicIds(topicIds);

        List<Long> specIds = cmsAppTopicDataDetailDtos.stream().map(CmsAppTopicDataDetailDto::getItemId).collect(Collectors.toList());
        if (specIds == null || specIds.size() == 0) {
            log.info("--- 该主题下没有内容 ---");
            return prodSpecInfoDtos;
        }

        ProdSpecInfoDto prodSpecInfoDto = new ProdSpecInfoDto();
        prodSpecInfoDto.setSpecIds(specIds);
        log.info(specIds.toString());
        Wrapper<List<ProdSpecInfoDto>> listProdSpecInfoDtoWrapper = pmcFeignApi.getSpecInfoDtosByCondition(prodSpecInfoDto);

        List<Long> shopInfoDtoList = new ArrayList<>();
        shopInfoDtoList.add(cmsAppTopicDataDetailDto.getShopId());
        System.out.println("CMC+++++++++cmsApptopicdataserviceImpl=++++++++shopInfoDtoList="+shopInfoDtoList);
        List<ShopInfoDto> shopRegion = smcFeignApi.getShopInfoByShopIds(shopInfoDtoList);
        Long regionCityId = shopRegion.get(0).getRegionCityId();
        String regionCityName = shopRegion.get(0).getRegionCityName();

        Long wareHouseId = 0L;
        Wrapper  warehouseidWrapper= wmcFeignApi.getwarehouseidbyshopid(cmsAppTopicDataDetailDto.getShopId());
        wareHouseId = Long.valueOf(warehouseidWrapper.getResult().toString());

        Wrapper  cityStockCountWrapper = wmcFeignApi.getWarehouseStockCount(wareHouseId,specIds);
        Map<String,Integer>  stockCounts = (Map)cityStockCountWrapper.getResult();

        if (listProdSpecInfoDtoWrapper.error()) {
            log.error("--- pmcFeignApi.getSpecInfoDtosByCondition(prodSpecInfoDto)内部异常，参数：{} ---", prodSpecInfoDto);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        prodSpecInfoDtos = listProdSpecInfoDtoWrapper.getResult();

        List<ProdSpecInfoDto> list = new ArrayList<>();
        for (Long specId : specIds) {
            if (prodSpecInfoDtos!=null&prodSpecInfoDtos.size()>0){
                for (ProdSpecInfoDto specInfoDto : prodSpecInfoDtos) {
                    if (specId.equals(specInfoDto.getSpecId())){
                        specInfoDto.setWareCityId(regionCityId);
                        specInfoDto.setWareCityName(regionCityName);
                        specInfoDto.setWarehouseId(wareHouseId);

                        Iterator iter = stockCounts.entrySet().iterator();
                        while (iter.hasNext()) {
                            Map.Entry entry = (Map.Entry) iter.next();
                            Object key = entry.getKey();
                            Object val = entry.getValue();
                            if (key.toString().equals(specInfoDto.getSpecId().toString())){
                                specInfoDto.setStockCount(Integer.valueOf(val.toString()));
                            }
                        }
                        list.add(specInfoDto);
                    }
                }
            }

        }


        log.info("--- Leave getAppDetailByTopicId(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto)，返回值大小：{} ---", prodSpecInfoDtos.size());

        return list;
    }

    @Override
    public List<CmsAppTopicDataDetailDto> getAppDetailByTopicIds(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto) {
        log.info("--- Enter getAppDetailByTopicIds(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto)，参数：{} ---", cmsAppTopicDataDetailDto);
        List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtoList = new ArrayList<>();
        if (cmsAppTopicDataDetailDto.getTopicIds() == null || "".equals(cmsAppTopicDataDetailDto.getTopicIds())) {
            log.info("--- 传入的主题id为null ---");
            return cmsAppTopicDataDetailDtoList;
        }
        if (cmsAppTopicDataDetailDto!=null){
            if (cmsAppTopicDataDetailDto.getShopId()==null){
                cmsAppTopicDataDetailDto.setShopId(220854931912392704L);
            }
        }
        List<Long> topicIds = Arrays.asList(cmsAppTopicDataDetailDto.getTopicIds().split(",")).stream().map(topicId -> Long.valueOf(topicId)).collect(Collectors.toList());
        for (Long topicId : topicIds) {
            List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos = cmsAppTopicDataMapper.getAppListByTopicId(topicId);
            //dataType数据类型，1：商品类；2：厂家类；3：地域类；4：店铺类；5：其他。
            if (cmsAppTopicDataDetailDtos.size() > 0) {
                Integer dataType = cmsAppTopicDataDetailDtos.get(0).getDataType();
                switch (dataType.toString()) {
                    case "1":
                    case "99":
                        log.info("--- dataType数据类型为：1、99，代表：商品类 ---");
                        //cmsAppTopicDataDetailDtos = getProdDetail(cmsAppTopicDataDetailDtos,cmsAppTopicDataDetailDto.getShopId(),cmsAppTopicDataDetailDto.getLongitude(), cmsAppTopicDataDetailDto.getLatitude());
                        cmsAppTopicDataDetailDtos = getProdDetail(cmsAppTopicDataDetailDtos,cmsAppTopicDataDetailDto.getShopId(),"0", "0");
                        break;
                    case "2":
                        log.info("--- dataType数据类型为：2，代表：厂家类 ---");
                        cmsAppTopicDataDetailDtos = getFactoryDetail(cmsAppTopicDataDetailDtos);
                        break;
                    case "3":
                        log.info("--- dataType数据类型为：3，代表：地理信息类 ---");
                        cmsAppTopicDataDetailDtos = getRegionIntroduceInfoByIds(cmsAppTopicDataDetailDtos);
                        break;
                    case "4":
                        log.info("--- dataType数据类型为：4，代表：店铺类 ---");
                        cmsAppTopicDataDetailDtos = getShopDetail(cmsAppTopicDataDetailDtos);
                        break;
                }
                cmsAppTopicDataDetailDtoList.addAll(cmsAppTopicDataDetailDtos);
            } else {
                log.info("--- 该主题下没有内容 ---");
            }
        }
//        log.info("--- Leave getAppDetailByTopicIds(CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto)，返回值：{} ---", cmsAppTopicDataDetailDtoList);

        return cmsAppTopicDataDetailDtoList;
    }

    private List<CmsAppTopicDataDetailDto> getProdDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos, Long shopId, String longitude, String latitude) {
       // log.info("--- Enter getProdDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos, String longitude, String latitude)方法，参数：{},{},{} ---", cmsAppTopicDataDetailDtos, longitude, latitude);
        List<Long> specIds = cmsAppTopicDataDetailDtos.stream().map(CmsAppTopicDataDetailDto::getItemId).collect(Collectors.toList());
        if (specIds == null || specIds.size() == 0) {
            log.info("--- 该主题下没有内容 ---");
            return cmsAppTopicDataDetailDtos;
        }
        ProdSpecInfoDto prodSpecInfoDto = new ProdSpecInfoDto();
        prodSpecInfoDto.setSpecIds(specIds);
        Wrapper<List<ProdSpecInfoDto>> listProdSpecInfoDtoWrapper = pmcFeignApi.getSpecInfoDtosByCondition(prodSpecInfoDto);
        if (listProdSpecInfoDtoWrapper == null) {
            log.error("--- pmcFeignApi.getSpecInfoDtosByCondition(prodSpecInfoDto)内部异常，参数：{} ---", prodSpecInfoDto);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        List<ProdSpecInfoDto> prodSpecInfoDtos = listProdSpecInfoDtoWrapper.getResult();
        if (prodSpecInfoDtos == null || prodSpecInfoDtos.size() == 0) {
            return cmsAppTopicDataDetailDtos;
        }


        //2019.10.22 添加仓库城市名称、Id、CityId
        Long regionCityId = 0L;
        String regionCityName = "";
        Long wareHouseId = 0L;



        List<Long> shopInfoDtoList = new ArrayList<>();
        shopInfoDtoList.add(shopId);
        System.out.println("CMC++++++++cmsApptopicDataServiceImpl.getProdDetail ====="+shopId);
        List<ShopInfoDto> shopRegion = smcFeignApi.getShopInfoByShopIds(shopInfoDtoList);




        if (shopRegion!=null && shopRegion.size()>0){
            regionCityId  = shopRegion.get(0).getRegionCityId();
            regionCityName = shopRegion.get(0).getRegionCityName();
        }

        Wrapper  warehouseidWrapper= wmcFeignApi.getwarehouseidbyshopid(shopId);
        wareHouseId = Long.valueOf(warehouseidWrapper.getResult().toString());


        Wrapper  cityStockCountWrapper = wmcFeignApi.getWarehouseStockCount(wareHouseId,specIds);
        Map<String,Integer>  stockCounts = (Map)cityStockCountWrapper.getResult();

        for (CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto : cmsAppTopicDataDetailDtos) {
            for (ProdSpecInfoDto prodSpecInfo : prodSpecInfoDtos) {
                if (prodSpecInfo.getSpecId().equals(cmsAppTopicDataDetailDto.getItemId())) {
                    prodSpecInfo.setWareCityId(regionCityId);
                    prodSpecInfo.setWareCityName(regionCityName);
                    prodSpecInfo.setWarehouseId(wareHouseId);

                    Iterator iter = stockCounts.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        Object key = entry.getKey();
                        Object val = entry.getValue();
                        if (key.toString().equals(prodSpecInfo.getSpecId().toString())){
                            prodSpecInfo.setStockCount(Integer.valueOf(val.toString()));
                        }
                    }

                    cmsAppTopicDataDetailDto.setProdSpecInfoDto(prodSpecInfo);
                }
            }
        }


        //log.info("--- Leave getProdDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos, String longitude, String latitude)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        log.info("--- Leave getProdDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos, String longitude, String latitude)方法 ---");
        return cmsAppTopicDataDetailDtos;
    }

    @Override
    public List<CmsAppTopicDataDetailDto> getFactoryDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos) {
        //log.info("--- Enter getFactoryDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        List<Long> factoryIds = cmsAppTopicDataDetailDtos.stream().map(CmsAppTopicDataDetailDto::getItemId).collect(Collectors.toList());
        if (factoryIds == null || factoryIds.size() == 0) {
            log.info("--- 该主题下没有内容 ---");
            return cmsAppTopicDataDetailDtos;
        }
        Wrapper<List<FactoryInfoDto>> factoryInfosWrapper = pmcFeignApi.getFactoryDetail(factoryIds);
        if (factoryInfosWrapper.error()) {
            log.error("--- pmcFeignApi.getFactoryDetail(factoryIds)内部异常，参数：{} ---", factoryIds);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        List<FactoryInfoDto> factoryInfoDtos = factoryInfosWrapper.getResult();
        for (CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto : cmsAppTopicDataDetailDtos) {
            for (FactoryInfoDto factoryInfoDto : factoryInfoDtos) {
                if (factoryInfoDto.getFactoryId().equals(cmsAppTopicDataDetailDto.getItemId())) {
                    cmsAppTopicDataDetailDto.setFactoryInfoDto(factoryInfoDto);
                }
            }
        }
        //log.info("--- Leave getFactoryDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        return cmsAppTopicDataDetailDtos;
    }

    @Override
    public List<CmsAppTopicDataDetailDto> getRegionIntroduceInfoByIds(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos) {
        //log.info("--- Enter getRegionIntroduceInfoByIds(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        List<Long> regionIds = cmsAppTopicDataDetailDtos.stream().map(CmsAppTopicDataDetailDto::getItemId).collect(Collectors.toList());
        if (regionIds == null || regionIds.size() == 0) {
            log.info("--- 该主题下没有内容 ---");
            return cmsAppTopicDataDetailDtos;
        }
        Wrapper<List<RegionInfoDto>> regionInfosWrapper= pmcFeignApi.getRegionIntroduceInfoByIds(regionIds);
        if (regionInfosWrapper.error()) {
            log.error("--- pmcFeignApi.getRegionIntroduceInfoByIds(regionIds)内部异常，参数：{} ---", regionIds);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        List<RegionInfoDto> regionInfoDtos = regionInfosWrapper.getResult();
        for (CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto : cmsAppTopicDataDetailDtos) {
            for (RegionInfoDto regionInfoDto : regionInfoDtos) {
                if (regionInfoDto.getRegionId().equals(cmsAppTopicDataDetailDto.getItemId())) {
                    cmsAppTopicDataDetailDto.setRegionInfoDto(regionInfoDto);
                }
            }
        }
        //log.info("--- Leave getRegionIntroduceInfoByIds(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        return cmsAppTopicDataDetailDtos;
    }

    @Override
    public List<CmsAppTopicDataDetailDto> getShopDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos) {
        log.info("--- Enter getShopDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        List<Long> shopIds = cmsAppTopicDataDetailDtos.stream().map(CmsAppTopicDataDetailDto::getItemId).collect(Collectors.toList());
        if (shopIds == null || shopIds.size() == 0) {
            log.info("--- 该主题下没有内容 ---");
            return cmsAppTopicDataDetailDtos;
        }
        System.out.println("cmsApptopicDataServiceImpl.getshopDetail ====="+shopIds);
        List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopIds(shopIds);
        if (shopInfoDtos == null) {
            log.error("--- smcFeignApi.getShopInfoByShopIds(shopIds)内部异常，参数：{} ---", shopIds);
            throw new SmcBizException(ErrorCodeEnum.GL99990002);
        }
        for (CmsAppTopicDataDetailDto cmsAppTopicDataDetailDto : cmsAppTopicDataDetailDtos) {
            for (ShopInfoDto shopInfoDto : shopInfoDtos) {
                if (shopInfoDto.getShopId().equals(cmsAppTopicDataDetailDto.getItemId())) {
                    cmsAppTopicDataDetailDto.setShopInfoDto(shopInfoDto);
                }
            }
        }
        //log.info("--- Leave getShopDetail(List<CmsAppTopicDataDetailDto> cmsAppTopicDataDetailDtos)方法，返回值：{} ---", cmsAppTopicDataDetailDtos);
        return cmsAppTopicDataDetailDtos;
    }
}
